const app = getApp()
import { updateUserInfo, saveFile, getUserInfo } from '../../../api/index'
const uploadOss = require('../../../utils/upload/uploadImg.js')
import { uuid } from '../../../utils/util'

Page({
  data: {
    userInfo: {
      userInfo: {
        headImage: ''
      }
    },
    showInfoModal: false,
    basicInfo: {
      key: '',
      title: '',
      placeholder: ''
    },
    showAddressModal: false,
    showPwdModal: false,
    showGender: false,
    genderColumns: [
      { value: 1, label: '男', checked: false },
      { value: 2, label: '女', checked: false }
    ],
    currentGender: null
  },
  showGenderPop () {
    this.setData({ showGender: true })
  },
  selectGender ({ currentTarget: { dataset: { item, index } } }) {
    this.data.genderColumns.forEach(item => {
      item.checked = false
    })
    let key = `genderColumns[${index}].checked`
    this.setData({ [key]: true, genderColumns: this.data.genderColumns, currentGender: item })
  },
  async confirmGender () {
    try {
      if (!this.data.currentGender) {
        wx.showToast({ title: '请选择要修改的性别', icoon: 'none' })
        return
      }
      await updateUserInfo({ gender: this.data.currentGender.value })
      wx.showToast({ title: '修改信息成功！', icon: 'none' })
      this.setData({ ['userInfo.userInfo.gender'] : this.data.currentGender.label, showGender: false, currentGender: null })
      app.globalData.userInfo = this.data.userInfo
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  cancelGender () {
    this.setData({ showGender: false, currentGender: null })
  },
  selectPwd () {
    this.setData({ showPwdModal: true })
  },
  closePwdPop () {
    this.setData({ showPwdModal: false })
  },
  async changePwd () {
    await this.getUserInfo()
    this.setData({ showPwdModal: false })
  },
  changeBasicInfo ({ currentTarget: { dataset: { key, title, placeholder } } }) {
    this.data.basicInfo.key = key
    this.data.basicInfo.title = title
    this.data.basicInfo.placeholder = placeholder
    this.data.basicInfo.value = this.data.userInfo.userInfo[key]
    this.setData({ basicInfo: this.data.basicInfo, showInfoModal: true })
  },
  closeInfoPop () {
    this.setData({ showInfoModal: false })
  },
  async changeInfo ({ detail }) {
    try {
      await updateUserInfo({ [`${detail.key}`]: detail.value })
      wx.showToast({ title: '修改信息成功！', icon: 'none' })
      this.setData({ ['userInfo.userInfo.' + detail.key] : detail.value, showInfoModal: false })
      app.globalData.userInfo = this.data.userInfo
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async changeBirth ({ detail: { value } }) {
    try {
      await updateUserInfo({ birth: value })
      wx.showToast({ title: '修改生日成功！', icon: 'none' })
      this.setData({ 'userInfo.userInfo.birth': value })
      app.globalData.userInfo = this.data.userInfo
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  selectAddress () {
    this.setData({ showAddressModal: true })
  },
  closeAddressPop () {
    this.setData({ showAddressModal: false })
  },
  async changeAddress ({ detail }) {
    try {
      await updateUserInfo({ province: detail[0].value, city: detail[1].value, area: detail[2].value })
      wx.showToast({ title: '修改地址成功！', icon: 'none' })
      this.setData({ ['userInfo.userInfo.city'] : `${detail[0].label}-${detail[1].label}-${detail[2].label}`, showAddressModal: false })
      app.globalData.userInfo = this.data.userInfo
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  changeHead () {
    let _this = this
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      async success (res) {
        try {
          wx.showLoading({ title: '上传图片中...', mask: true })
          const { fileUrl, fileName } = await _this.uploadFile(res.tempFiles[0], 'tempFilePath')
          const { ResultSet } = await saveFile({
            fileList: [{
              fileName: fileName,
              fileUrl: fileUrl
            }]
          })
          await updateUserInfo({ headImage: ResultSet.userData.fileIdList[0].fileId })
          _this.setData({ 'userInfo.userInfo.headImage': fileUrl })
          app.globalData.userInfo = _this.data.userInfo
          wx.hideLoading()
          wx.showToast({ title: '头像上传成功！', icon: 'none' })
        } catch (err) {
          wx.hideLoading()
          wx.showToast({ title: '上传失败！', icon: 'none' })
          console.log(err)
        }
      }
    })
  },
  uploadFile (item, key, files = '', index = '', that = '', dataKey = '') {
    return new Promise((resolve, reject) => {
      uploadOss(item[key],
        (res) => {
          resolve(res)
        },
        (err) => {
          reject(err)
        },
        files, index, that, dataKey
      )
    })
  },
  async getUserInfo () {
    try {
      const { ResultSet } = await getUserInfo()
      if (!ResultSet.userData.userInfo || !ResultSet.userData.userInfo.userId) {
        wx.showToast({ title: '用户未登录', icon: 'none' })
        wx.$nav.navigateTo('/pages/login/index')
      } else {
        app.globalData.userInfo = ResultSet.userData.userInfo
        this.setData({
          userInfo: ResultSet.userData
        })
      }
    } catch (err) {
      console.log(err)
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  onLoad () {
    this.getUserInfo()
  }
})